<!-- 波形分析图表组件 - 简洁版 -->
<template>
  <div class="waveform-chart-container">
    <!-- 图表容器 -->
    <div ref="chartContainer" class="chart-container"></div>
    
    <!-- 简洁控制面板 -->
    <div class="waveform-controls">
      <!-- 主要参数 -->
      <div class="main-controls">
        <div class="control-item">
          <span class="label">时间</span>
          <div class="time-range">
            <input 
              v-model="timeRange[0]" 
              type="number" 
              class="time-input"
              @change="updateTimeRange"
            />
            <span class="separator">~</span>
            <input 
              v-model="timeRange[1]" 
              type="number" 
              class="time-input"
              @change="updateTimeRange"
            />
            <span class="unit">ms</span>
          </div>
        </div>
        
        <div class="control-item">
          <span class="label">采样率</span>
          <select v-model="sampleRate" class="sample-select" @change="changeSampleRate">
            <option value="1000">1 kHz</option>
            <option value="10000">10 kHz</option>
            <option value="100000">100 kHz</option>
            <option value="1000000">1 MHz</option>
          </select>
        </div>
        
        <div class="control-item">
          <span class="label">滤波</span>
          <div class="filter-tabs">
            <button 
              v-for="filter in filterOptions"
              :key="filter.value"
              :class="['filter-tab', { active: filterType === filter.value }]"
              @click="setFilter(filter.value)"
            >
              {{ filter.label }}
            </button>
          </div>
        </div>
      </div>

      <!-- 播放控制 -->
      <div class="playback-controls">
        <div class="play-buttons">
          <button :class="['play-btn', { disabled: isPlaying }]" @click="startPlayback">
            <svg viewBox="0 0 24 24" class="btn-icon">
              <path fill="currentColor" d="M8 5v14l11-7z"/>
            </svg>
          </button>
          <button :class="['play-btn', { disabled: !isPlaying }]" @click="pausePlayback">
            <svg viewBox="0 0 24 24" class="btn-icon">
              <path fill="currentColor" d="M6 4h4v16H6V4zm8 0h4v16h-4V4z"/>
            </svg>
          </button>
          <button class="play-btn" @click="stopPlayback">
            <svg viewBox="0 0 24 24" class="btn-icon">
              <path fill="currentColor" d="M6 4h12v16H6z"/>
            </svg>
          </button>
          <button class="play-btn" @click="resetPlayback">
            <svg viewBox="0 0 24 24" class="btn-icon">
              <path fill="currentColor" d="M4 12c0-4.42 3.58-8 8-8s8 3.58 8 8-3.58 8-8 8-8-3.58-8-8zm14 0c0-3.31-2.69-6-6-6s-6 2.69-6 6 2.69 6 6 6 6-2.69 6-6z"/>
            </svg>
          </button>
        </div>
        
        <div class="progress-container">
          <input 
            v-model="playbackPosition" 
            type="range" 
            :min="0" 
            :max="100"
            class="progress-slider"
            @input="seekToPosition"
          />
          <div class="time-display">{{ currentTime }}ms / {{ totalTime }}ms</div>
        </div>
      </div>
    </div>

    <!-- 分析结果 -->
    <div class="analysis-panel" v-if="analysisResult">
      <div class="analysis-header">
        <div class="analysis-title">波形分析</div>
        <button class="close-btn" @click="closeAnalysis">×</button>
      </div>
      <div class="analysis-content">
        <div class="analysis-grid">
          <div class="analysis-item">
            <div class="analysis-label">峰值</div>
            <div class="analysis-value">{{ analysisResult.peak }}</div>
          </div>
          <div class="analysis-item">
            <div class="analysis-label">均值</div>
            <div class="analysis-value">{{ analysisResult.mean }}</div>
          </div>
          <div class="analysis-item">
            <div class="analysis-label">RMS</div>
            <div class="analysis-value">{{ analysisResult.rms }}</div>
          </div>
          <div class="analysis-item">
            <div class="analysis-label">频率</div>
            <div class="analysis-value">{{ analysisResult.frequency }}</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 统计信息 -->
    <div class="stats-panel">
      <div class="stat-item">
        <div class="stat-value">{{ waveformData.length }}</div>
        <div class="stat-label">采样点</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ signalStrength }}</div>
        <div class="stat-label">信号强度</div>
      </div>
      <div class="stat-item">
        <div class="stat-value">{{ snrRatio }}</div>
        <div class="stat-label">信噪比</div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'

// Props
const props = defineProps({
  waveformData: {
    type: Array,
    default: () => []
  },
  timeRange: {
    type: Array,
    default: () => [0, 100]
  },
  isPlaying: {
    type: Boolean,
    default: false
  }
})

// Emits
const emit = defineEmits(['timeRangeChange', 'amplitudeSelect'])

// 组件引用
const chartContainer = ref(null)

// 图表实例
let chartInstance = null
let playbackTimer = null

// 响应式数据
const timeRange = ref([...props.timeRange])
const amplitudeRange = ref([-1.5, 1.5])
const sampleRate = ref('100000')
const filterType = ref('none')
const playbackPosition = ref(0)
const analysisResult = ref(null)
const isPlaying = ref(false)

// 滤波选项
const filterOptions = ref([
  { value: 'none', label: '无' },
  { value: 'lowpass', label: '低通' },
  { value: 'highpass', label: '高通' },
  { value: 'bandpass', label: '带通' }
])

// 计算属性
const currentTime = computed(() => {
  return Math.round((playbackPosition.value / 100) * (timeRange.value[1] - timeRange.value[0]))
})

const totalTime = computed(() => {
  return timeRange.value[1] - timeRange.value[0]
})

const signalStrength = computed(() => {
  if (!props.waveformData.length) return '-'
  const rms = Math.sqrt(props.waveformData.reduce((sum, point) => sum + point.amplitude * point.amplitude, 0) / props.waveformData.length)
  return `${(rms * 100).toFixed(1)}%`
})

const snrRatio = computed(() => {
  if (!props.waveformData.length) return '-'
  const signal = Math.max(...props.waveformData.map(p => Math.abs(p.amplitude)))
  const noise = 0.1
  const snr = 20 * Math.log10(signal / noise)
  return `${snr.toFixed(1)}dB`
})

// 初始化图表
const initChart = () => {
  if (!chartContainer.value) return

  chartInstance = echarts.init(chartContainer.value, 'dark')
  
  const option = {
    backgroundColor: 'transparent',
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '5%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '时间 (ms)',
      nameLocation: 'center',
      nameGap: 25,
      min: timeRange.value[0],
      max: timeRange.value[1],
      axisLine: {
        lineStyle: { color: 'rgba(0, 212, 255, 0.3)' }
      },
      axisLabel: {
        color: '#8591a3',
        fontSize: 11
      },
      splitLine: {
        lineStyle: { color: 'rgba(0, 212, 255, 0.1)' }
      }
    },
    yAxis: {
      type: 'value',
      name: '幅度',
      nameLocation: 'center',
      nameGap: 40,
      min: amplitudeRange.value[0],
      max: amplitudeRange.value[1],
      axisLine: {
        lineStyle: { color: 'rgba(0, 212, 255, 0.3)' }
      },
      axisLabel: {
        color: '#8591a3',
        fontSize: 11
      },
      splitLine: {
        lineStyle: { color: 'rgba(0, 212, 255, 0.1)' }
      }
    },
    tooltip: {
      trigger: 'axis',
      backgroundColor: 'rgba(0, 0, 0, 0.8)',
      borderColor: '#00d4ff',
      borderWidth: 1,
      textStyle: { color: '#fff', fontSize: 12 },
      formatter: (params) => {
        const point = params[0]
        return `时间: ${point.data[0]} ms<br/>幅度: ${point.data[1].toFixed(3)}`
      }
    },
    series: [
      {
        name: '波形',
        type: 'line',
        data: props.waveformData.map(point => [point.time, point.amplitude]),
        lineStyle: {
          color: '#00d4ff',
          width: 1.5
        },
        smooth: false,
        symbol: 'none',
        sampling: 'lttb'
      }
    ],
    animation: false
  }

  chartInstance.setOption(option)

  // 添加点击事件
  chartInstance.on('click', (params) => {
    if (params.seriesIndex === 0) {
      const time = params.data[0]
      const amplitude = params.data[1]
      
      performAnalysis(time, amplitude)
      emit('amplitudeSelect', amplitude)
    }
  })
}

// 更新图表
const updateChart = () => {
  if (!chartInstance) return

  const option = {
    xAxis: {
      min: timeRange.value[0],
      max: timeRange.value[1]
    },
    yAxis: {
      min: amplitudeRange.value[0],
      max: amplitudeRange.value[1]
    },
    series: [
      {
        data: props.waveformData.map(point => [point.time, point.amplitude])
      }
    ]
  }

  chartInstance.setOption(option)
}

// 执行波形分析
const performAnalysis = (time, amplitude) => {
  const dataSlice = props.waveformData.filter(p => Math.abs(p.time - time) <= 10)
  
  if (dataSlice.length > 0) {
    const amplitudes = dataSlice.map(p => p.amplitude)
    const peak = Math.max(...amplitudes.map(Math.abs))
    const mean = amplitudes.reduce((sum, val) => sum + val, 0) / amplitudes.length
    const rms = Math.sqrt(amplitudes.reduce((sum, val) => sum + val * val, 0) / amplitudes.length)
    
    analysisResult.value = {
      peak: peak.toFixed(3),
      mean: mean.toFixed(3),
      rms: rms.toFixed(3),
      frequency: `${(Math.random() * 1000 + 100).toFixed(1)} Hz`
    }
  }
}

// 时间范围更新
const updateTimeRange = () => {
  if (timeRange.value[0] >= timeRange.value[1]) {
    timeRange.value[1] = timeRange.value[0] + 10
  }
  updateChart()
  emit('timeRangeChange', timeRange.value)
}

// 采样率变化
const changeSampleRate = (event) => {
  const rate = event.target.value
  ElMessage.info(`采样率: ${parseInt(rate) / 1000}kHz`)
}

// 设置滤波器
const setFilter = (filter) => {
  filterType.value = filter
  const filterNames = {
    none: '无滤波',
    lowpass: '低通滤波',
    highpass: '高通滤波',
    bandpass: '带通滤波'
  }
  ElMessage.info(`${filterNames[filter]}`)
}

// 播放控制
const startPlayback = () => {
  if (isPlaying.value) return
  isPlaying.value = true
  playbackTimer = setInterval(() => {
    playbackPosition.value += 1
    if (playbackPosition.value >= 100) {
      stopPlayback()
    }
  }, 50)
}

const pausePlayback = () => {
  isPlaying.value = false
  if (playbackTimer) {
    clearInterval(playbackTimer)
    playbackTimer = null
  }
}

const stopPlayback = () => {
  isPlaying.value = false
  playbackPosition.value = 0
  if (playbackTimer) {
    clearInterval(playbackTimer)
    playbackTimer = null
  }
}

const resetPlayback = () => {
  stopPlayback()
  analysisResult.value = null
}

const seekToPosition = (event) => {
  playbackPosition.value = event.target.value
}

// 关闭分析结果
const closeAnalysis = () => {
  analysisResult.value = null
}

// 监听数据变化
watch(() => props.waveformData, () => {
  updateChart()
}, { deep: true })

watch(() => props.timeRange, (newRange) => {
  timeRange.value = [...newRange]
  updateChart()
})

// 窗口大小变化
const handleResize = () => {
  if (chartInstance) {
    chartInstance.resize()
  }
}

// 生命周期
onMounted(() => {
  nextTick(() => {
    initChart()
  })
  window.addEventListener('resize', handleResize)
})

onBeforeUnmount(() => {
  if (playbackTimer) {
    clearInterval(playbackTimer)
  }
  if (chartInstance) {
    chartInstance.dispose()
    chartInstance = null
  }
  window.removeEventListener('resize', handleResize)
})

// 暴露方法
defineExpose({
  play: startPlayback,
  pause: pausePlayback,
  stop: stopPlayback,
  reset: resetPlayback,
  updateChart
})
</script>

<style scoped>
.waveform-chart-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: linear-gradient(135deg, #0a0f1b 0%, #1a2332 100%);
  border-radius: 0.8vh;
  border: 1px solid rgba(0, 212, 255, 0.2);
  overflow: hidden;
  position: relative;
}

/* 图表容器 */
.chart-container {
  flex: 1;
  min-height: 0;
  position: relative;
}

/* 控制面板 */
.waveform-controls {
  padding: 1.5vh 2vw;
  background: rgba(0, 0, 0, 0.4);
  backdrop-filter: blur(10px);
  border-top: 1px solid rgba(0, 212, 255, 0.1);
}

.main-controls {
  display: flex;
  gap: 3vw;
  margin-bottom: 1.5vh;
  align-items: center;
}

.control-item {
  display: flex;
  align-items: center;
  gap: 1vw;
}

.label {
  font-size: 0.9rem;
  color: #8591a3;
  min-width: 3vw;
}

.time-range {
  display: flex;
  align-items: center;
  gap: 0.5vw;
}

.time-input {
  width: 3.5vw;
  padding: 0.3vh 0.5vw;
  background: rgba(0, 212, 255, 0.1);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 0.3vh;
  color: #00d4ff;
  font-size: 0.8rem;
  text-align: center;
}

.time-input:focus {
  outline: none;
  border-color: #00d4ff;
  box-shadow: 0 0 0 0.1vh rgba(0, 212, 255, 0.3);
}

.separator {
  color: #8591a3;
  margin: 0 0.3vw;
}

.unit {
  font-size: 0.8rem;
  color: #8591a3;
}

.sample-select {
  padding: 0.3vh 0.8vw;
  background: rgba(0, 212, 255, 0.1);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 0.3vh;
  color: #00d4ff;
  font-size: 0.8rem;
}

.sample-select:focus {
  outline: none;
  border-color: #00d4ff;
}

.filter-tabs {
  display: flex;
  gap: 0.3vw;
}

.filter-tab {
  padding: 0.3vh 0.8vw;
  background: rgba(0, 212, 255, 0.1);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 0.3vh;
  color: #8591a3;
  font-size: 0.7rem;
  cursor: pointer;
  transition: all 0.2s ease;
}

.filter-tab:hover {
  background: rgba(0, 212, 255, 0.2);
  color: #00d4ff;
}

.filter-tab.active {
  background: rgba(0, 212, 255, 0.3);
  border-color: #00d4ff;
  color: #00d4ff;
}

/* 播放控制 */
.playback-controls {
  display: flex;
  align-items: center;
  gap: 2vw;
}

.play-buttons {
  display: flex;
  gap: 0.5vw;
}

.play-btn {
  width: 3vh;
  height: 3vh;
  background: rgba(0, 212, 255, 0.2);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 0.4vh;
  color: #00d4ff;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.play-btn:hover:not(.disabled) {
  background: rgba(0, 212, 255, 0.3);
  transform: translateY(-0.1vh);
}

.play-btn.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.btn-icon {
  width: 1.5vh;
  height: 1.5vh;
}

.progress-container {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 1vw;
}

.progress-slider {
  flex: 1;
  height: 0.3vh;
  background: rgba(0, 212, 255, 0.2);
  border-radius: 0.15vh;
  outline: none;
  -webkit-appearance: none;
}

.progress-slider::-webkit-slider-thumb {
  width: 1vh;
  height: 1vh;
  background: #00d4ff;
  border-radius: 50%;
  cursor: pointer;
  -webkit-appearance: none;
}

.time-display {
  font-size: 0.8rem;
  color: #8591a3;
  min-width: 8vw;
}

/* 分析面板 */
.analysis-panel {
  position: absolute;
  top: 2vh;
  right: 2vw;
  width: 12vw;
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 212, 255, 0.3);
  border-radius: 0.6vh;
  overflow: hidden;
  z-index: 100;
}

.analysis-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1vh 1.5vw;
  background: rgba(0, 212, 255, 0.1);
  border-bottom: 1px solid rgba(0, 212, 255, 0.2);
}

.analysis-title {
  font-size: 0.9rem;
  color: #00d4ff;
  font-weight: 600;
}

.close-btn {
  background: none;
  border: none;
  color: #8591a3;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0;
  width: 2vh;
  height: 2vh;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.close-btn:hover {
  background: rgba(255, 107, 107, 0.2);
  color: #ff6b6b;
}

.analysis-content {
  padding: 1vh 1.5vw;
}

.analysis-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 0.8vh;
}

.analysis-item {
  text-align: center;
}

.analysis-label {
  font-size: 0.7rem;
  color: #8591a3;
  margin-bottom: 0.3vh;
}

.analysis-value {
  font-size: 0.9rem;
  color: #00d4ff;
  font-weight: 600;
}

/* 统计面板 */
.stats-panel {
  position: absolute;
  bottom: 2vh;
  right: 2vw;
  display: flex;
  gap: 1vw;
  z-index: 100;
}

.stat-item {
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(0, 212, 255, 0.2);
  border-radius: 0.5vh;
  padding: 1vh 1.2vw;
  text-align: center;
  min-width: 3.5vw;
}

.stat-value {
  font-size: 1rem;
  font-weight: 600;
  color: #00d4ff;
  margin-bottom: 0.3vh;
}

.stat-label {
  font-size: 0.7rem;
  color: #8591a3;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .main-controls {
    flex-direction: column;
    gap: 1vh;
    align-items: stretch;
  }
  
  .control-item {
    justify-content: space-between;
  }
  
  .playback-controls {
    flex-direction: column;
    gap: 1vh;
  }
  
  .analysis-panel {
    width: 15vw;
  }
  
  .stats-panel {
    flex-direction: column;
    gap: 0.5vh;
  }
}
</style>